package tenantchannellogic

import (
	"context"
	"math"

	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/tenant/channel"
	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/tenant/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UsdtListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUsdtListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UsdtListLogic {
	return &UsdtListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UsdtListLogic) UsdtList(in *rpc.UsdtListRequest) (*rpc.UsdtListResponse, error) {
	var (
		CommonResp rpc.CommonResp
		usdtList   []schema.TenantChannelUsdt
		count      int64
		err        error
		totalPage  int64
	)

	usdtModel := model.NewTenantChannelUsdtModel(l.ctx, l.svcCtx.Db)
	if in.UsdtType != "" {
		usdtList, err = usdtModel.GetUsdtByType(in.UsdtType)
	} else if in.Page.Page > 0 {
		if in.Page.PageSize > 10000 || in.Page.PageSize <= 0 {
			in.Page.PageSize = 20
		}
		count, usdtList, err = usdtModel.FindUsdtList(in.Page)
		if count > 0 {
			totalPage = int64(math.Ceil(float64(count) / float64(in.Page.PageSize)))
		}
	} else {
		usdtList, err = usdtModel.GetAllUsdt()
	}

	if err != nil {
		CommonResp.Code = xerrors.DBError
		CommonResp.Message = "Failed to fetch USDT list"
		return &rpc.UsdtListResponse{
			CommonResp: &CommonResp,
		}, err
	}

	var records []*rpc.Usdt
	for _, usdt := range usdtList {
		records = append(records, &rpc.Usdt{
			Id:        usdt.ID,
			CreatedAt: usdt.CreatedAt,
			UpdatedAt: usdt.UpdatedAt,
			UsdtType:  usdt.UsdtType,
			QrCode:    usdt.QrCode,
			Address:   usdt.Address,
			Sort:      usdt.Sort,
			Name:      usdt.Name,
			Status:    usdt.Status,
		})
	}

	CommonResp.Message = "Success"
	return &rpc.UsdtListResponse{
		Records:    records,
		CommonResp: &CommonResp,
		Pagination: &rpc.Pagination{
			PageSize:  uint32(in.Page.PageSize),
			Page:      uint32(in.Page.Page),
			Total:     count,
			TotalPage: totalPage,
		},
	}, nil
}
